import React from 'react'
import AppList from './AppList.js'
import AppForm from './AppForm.js'
import AppSearch from './AppSearch.js'
import AppFooter from './AppFooter.js'

class App extends React.Component {
    state = {
        choosevalue : 1,
        data: this.props.data
    }
  
    render () {
        const { data } = this.state; 
        return (
        <div className='ui comments'>
            <h1>My Todo with React</h1>
            <div className='ui divider'></div>
            <AppSearch
                SearchTodoItem={this.OnSearchTodoItem} />
            <AppForm 
                AddTodoItem={this.OnAddTodoItem} />
            <AppList 
                data={data}
                choosevalue={this.state.choosevalue}
                ChangeCompleteTop={this.AllChangeComplete}
                DeleteItemTop={this.AllOnDeleteItem}
            />
            <AppFooter 
                SubmitChooseValue={this.ChooseValue}
            />
        </div>
    )
  }

  
  ChooseValue = (id) => {
    this.setState({choosevalue:id});
  }

  OnAddTodoItem = (newItem) => {
    let newdata = this.state.data.concat(newItem);
    this.setState({data : newdata});
  }

  OnSearchTodoItem = (title) => {
    let newdata = this.state.data.map((item,index) => {
        if(title == ''){
            item.deleteFlag = false;
        }else if(item.text != title) {
            item.deleteFlag = true;
        }
        return item;
    })
    this.setState({data : newdata});
  }

  AllChangeComplete = (id) => {
      let newdata = this.state.data.map((item,index) => {
          if(item.id === id) {
              item.complete = !item.complete;
          }
          return item;
      })
      this.setState({data : newdata});
  }

  AllOnDeleteItem= (id) => {
      let newdata = this.state.data.map(function (item) {
          if(item.id == id){
            item.deleteFlag = true
          }
          return item
      })
      this.setState({data : newdata})
  }
}

export default App;